//goodscomment 收藏 backend
const router = require('koa-router')()
const fs = require("fs");
const path = require("path");
//这里路径后期需要改 不知道前端灰传到哪里？//已改
const uploadDir = path.join(__dirname, '../images/goodscomment');

router.prefix('/goodscomment')

//页面初始化时获取数据库内goodscomment commentimg的数据条目
router.post('/commentbackend', async (ctx, next) => {
    await ctx.db.EXCUTE("SET @@group_concat_max_len = 102400000000")
    let resultuserid = await ctx.db.EXCUTE("SELECT (SELECT username FROM user ni WHERE n.userid=ni.userid) AS userinfo FROM goodscomment n")
    let resultcommodityid = await ctx.db.EXCUTE("SELECT (SELECT com_name FROM buy ni WHERE n.commodityid=ni.commodityid) AS commodityinfo FROM goodscomment n")
    let result1 = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(imgs SEPARATOR '><') FROM commentimg ni WHERE n.comment_id=ni.comment_id) AS comings FROM goodscomment n")

    for (let i = 0; i < result1.length; i++) {
        result1[i].comings = (result1[i].comings || '').split('><');
        Object.assign(result1[i], resultuserid[i]);
        Object.assign(result1[i], resultcommodityid[i]);
    }

    ctx.body = {
        code: 200,
        data: result1
    }
})

//审核操作
router.post('/goodscommentauditbackend', async (ctx, next) => {
    let comment_id = ctx.request.body.comment_id;
    let sqlaudit = 'UPDATE goodscomment SET isAudit = 1 WHERE comment_id=?'
    await ctx.db.EXCUTE(sqlaudit, [comment_id]);

    await ctx.db.EXCUTE("SET @@group_concat_max_len = 102400000000")
    let resultuserid = await ctx.db.EXCUTE("SELECT (SELECT username FROM user ni WHERE n.userid=ni.userid) AS userinfo FROM goodscomment n")
    let resultcommodityid = await ctx.db.EXCUTE("SELECT (SELECT com_name FROM buy ni WHERE n.commodityid=ni.commodityid) AS commodityinfo FROM goodscomment n")
    let result1 = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(imgs SEPARATOR '><') FROM commentimg ni WHERE n.comment_id=ni.comment_id) AS comings FROM goodscomment n")

    for (let i = 0; i < result1.length; i++) {
        result1[i].comings = (result1[i].comings || '').split('><');
        Object.assign(result1[i], resultuserid[i]);
        Object.assign(result1[i], resultcommodityid[i]);
    }

    ctx.body = {
        code: 200,
        data: result1
    }
})

//审核不通过操作
router.post('/goodscommentauditFailedbackend', async (ctx, next) => {
    let comment_id = ctx.request.body.comment_id;
    let imgs = ctx.request.body.imgs;

    let sqlaudit = 'DELETE FROM goodscomment WHERE comment_id=?'
    await ctx.db.EXCUTE(sqlaudit, [comment_id]);

    //在数据库中删除commentimg表对应的文件
    for (let i = 0; i < imgs.length; i++) {
        let m = imgs[i].replace('/http://localhost:8080/', '')
        let n = imgs[i].split('http://localhost:8080/')[1]
        console.log(m);
        console.log(n);
        fs.unlink(path.join(__dirname, '../' + n), async function (err) {
            if (err) {
                console.log(err);
                ctx.body = {
                    code: 400
                }
            }
            await ctx.db.EXCUTE(`DELETE FROM commentimg WHERE comment_id=${comment_id}`)
        })
    }

    await ctx.db.EXCUTE("SET @@group_concat_max_len = 102400000000")
    let resultuserid = await ctx.db.EXCUTE("SELECT (SELECT username FROM user ni WHERE n.userid=ni.userid) AS userinfo FROM goodscomment n")
    let resultcommodityid = await ctx.db.EXCUTE("SELECT (SELECT com_name FROM buy ni WHERE n.commodityid=ni.commodityid) AS commodityinfo FROM goodscomment n")
    let result1 = await ctx.db.EXCUTE("SELECT n.*, (SELECT GROUP_CONCAT(imgs SEPARATOR '><') FROM commentimg ni WHERE n.comment_id=ni.comment_id) AS comings FROM goodscomment n")

    for (let i = 0; i < result1.length; i++) {
        result1[i].comings = (result1[i].comings || '').split('><');
        Object.assign(result1[i], resultuserid[i]);
        Object.assign(result1[i], resultcommodityid[i]);
    }

    ctx.body = {
        code: 200,
        data: result1
    }
})


//页面加载完成时获取commentimg全部的数据
router.post('/commentimgbackend', async (ctx, next) => {
    let result = await ctx.db.EXCUTE('SELECT * FROM commentimg ORDER BY comimg_id');
    ctx.body = {
        code: 200,
        data: result
    }
})


// 获取某商品下的评论
router.post('getcomment', async (ctx, next) => {
    console.log(ctx.request.body);
    let cresultcommodityidid = ctx.request.body.commodityid;
    console.log(commodityid);
    let result = await ctx.db.EXCUTE("select * from goodscomment where commodityid=" + commodityid);
    for (let i = 0; i < result.length; i++) {
        result[i].commentimgs = await ctx.db.EXCUTE("select * from commentimg where commodityid=" + result[i].comment_id);
        result[i].avatar = await ctx.db.EXCUTE("select avatar from user where userid=" + result[i].userid);
    }
    console.log(result);
    ctx.body = {
        code: 200,
        data: result
    }
})


// 对某商品进行评论
router.post('/evalu', async (ctx, next) => {
    console.log(ctx.request.body);
    let commodityid = ctx.request.body.commodityid
    let userid = ctx.request.body.userid
    let comment_text = ctx.request.body.text
    let nickname = ctx.request.body.nickname
    let img = ctx.request.body.img
    let comment_id = new Date().getTime() + Math.round(Math.random() * (1000 - 1) + 1)

    // let sql = "insert into (select * from goodscomment inner join commentimg on goodscomment.comment_id = commentimg.comment_id) (commodityid, userid, comment_text, nickname, imgs) values (?, ?, ?, ?, ?)"
    let sql = "insert into goodscomment (commodityid, userid, comment_text, nickname, comment_id) values (?, ?, ?, ?, ?)"
    let result = await ctx.db.EXCUTE(sql, [commodityid, userid, comment_text, nickname, comment_id])
    // let sql1 = "insert into commentimg (comment_id, imgs) values (?, ?)"
    // let result1 = await ctx.db.EXCUTE(sql, [comment_id, img[0]])
    // for (let i = 0; i < img.length; i++) {
    //     let sql1 = "insert into commentimg (comment_id, imgs) values (?, ?)"
    //     let result1 = await ctx.db.EXCUTE(sql1, [comment_id, img[i]])
    // }
    console.log(99999999);
    console.log(img);
    for (let i in img) {
        // console.log(ctx.request.body.data.list.length);
        let base64 = img[i];
        let dataBuffer = Buffer.from(base64, 'base64');
        console.log(dataBuffer);
        let name = Date.now() + Math.floor(Math.random()) + '.jpg'
        let imgUrl = uploadDir + '\\' + name
        fs.writeFileSync(imgUrl, dataBuffer)
        let sql1 = "insert into commentimg (comment_id, imgs) values (?, ?)"
        console.log(name);
        let result1 = await ctx.db.EXCUTE(sql1, [comment_id, '/images/goodscomment/' + name])
    }
    ctx.body = {
        code: 200,
        data: result
    }
})

router.post('/delete', async (ctx, next) => {
    let comment_id = ctx.request.body.comment_id
    let sql = 'delete from goodscomment where comment_id = ?';
    let result = await ctx.db.EXCUTE(sql, [comment_id]);
    if (result.affectedRows != 0) {
        ctx.body = {
            code: 200,
        }
    }
})

module.exports = router